package com.ruoyi.common.config;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * @author zxg
 * @date 2023-07-03
 * @Desc 自动填充数据
 */
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        log.info("新增");
        if(metaObject.hasGetter(Constants.DEFAULT_FIELD_COMPANY_ID)){
            this.fillStrategy(metaObject,Constants.DEFAULT_FIELD_COMPANY_ID, SecurityUtils.getLoginUser().getCompanyId());
        }
        if(metaObject.hasGetter(Constants.DEFAULT_FIELD_CREATE_BY)){
            this.fillStrategy(metaObject,Constants.DEFAULT_FIELD_CREATE_BY, SecurityUtils.getUserName());
        }
        if(metaObject.hasGetter(Constants.DEFAULT_FIELD_CREATE_DATE)){
            this.fillStrategy(metaObject,Constants.DEFAULT_FIELD_CREATE_DATE, LocalDateTime.now());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        log.info("修改");
        if(metaObject.hasGetter(Constants.DEFAULT_FIELD_UPDATE_BY)){
            this.fillStrategy(metaObject,Constants.DEFAULT_FIELD_UPDATE_BY, SecurityUtils.getUserName());
        }
        if(metaObject.hasGetter(Constants.DEFAULT_FIELD_UPDATE_DATE)){
            this.fillStrategy(metaObject,Constants.DEFAULT_FIELD_UPDATE_DATE, LocalDateTime.now());
        }
    }
}
